<?php
namespace app\admin2\controller;

use app\common\controller\AdminBaseo;
use app\common\model\Users as UsersModel;
use app\common\model\WxUser as WxUserModel;
use app\common\model\AuthorWxUser as AuthorWxUserModel;
use app\common\util\WechatAuthorUtil as WechatModel;
use app\common\util\WechatThirdUtil;
use think\Session;
use think\Db;
use think\Config;

/**
 * 后台首页
 * Class Index
 * @package app\admin\controller
 */
class Index extends AdminBaseo
{
    protected $wechat_obj;
    protected $wechat_author_util;
    protected $author_wx_user;
    protected $config;
    protected $wx_user;
    protected $users_model;

    protected function _initialize()
    {
        parent::_initialize();
        $this->wx_user = new WxUserModel();
        $this->author_wx_user = new AuthorWxUserModel();
        $this->config = $this->wx_user->find();
        $this->wechat_author_util = new WechatModel($this->config);
    }

    /**
     * 首页
     * @return mixed
     */
    public function index($id = '')
    {
        if(!empty($id)){
            $admin_id = session::get('admin_id');
            if($admin_id == 1){
                $where = ['id' => ['eq',$id]];
            }else{
                $where = [
                    'uid'=>['eq',$admin_id],
                    'id' => ['eq',$id],
                ];
            }

            $wechat_info = Db::name('author_wx_user')->where($where)->find();
            if(!$wechat_info) return false;
            Session::set('wechat_info' , $wechat_info);
        }elseif(Session::has('wechat_info')){
            $wechat_info = Session::get('wechat_info');
        }else{
            $this->redirect('/admin/publicnum/index');
        }

        $count = Db::name('users')->field('COUNT(*) total,COUNT(CASE WHEN subscribe = 1 THEN 1 ELSE NULL END) subscount,COUNT(CASE WHEN subscribe = 0 THEN 1 ELSE NULL END ) un_subscount,COUNT(CASE WHEN repeat_subscribe = 1 && subscribe = 1 THEN 1 ELSE NULL END) repeat_subscribe_count,COUNT(CASE WHEN is_second_unsubscribe = 1 THEN 1 ELSE NULL END) as second_unsubscribe_count')
                                  ->where('auid',$wechat_info['id'])
                                  ->select();//关注人数
        $this->assign('count',$count[0]);

        $version = Db::query('SELECT VERSION() AS ver');
        $config  = [
            'url'             => $_SERVER['HTTP_HOST'],
            'document_root'   => $_SERVER['DOCUMENT_ROOT'],
            'server_os'       => PHP_OS,
            'server_port'     => $_SERVER['SERVER_PORT'],
            'server_soft'     => $_SERVER['SERVER_SOFTWARE'],
            'php_version'     => PHP_VERSION,
            'mysql_version'   => $version[0]['ver'],
            'max_upload_size' => ini_get('upload_max_filesize')
        ];

        return $this->fetch('index', ['config' => $config]);
    }

    public function subtime(){
        $data = $this->request->param();
        if(Session::has('wechat_info')){
            $wechat_info = Session::get('wechat_info');
            $where = ['auid' => ['eq',$wechat_info['id']]];
            $whereOr = [];
            if($data['start_time'] != 0 && $data['end_time'] != 0){
                $where['subscribe_time'] = ['between',[$data['start_time'],$data['end_time']]];
                $whereOr['unsubscribe_time'] = ['between',[$data['start_time'],$data['end_time']]];
            }
            $count = Db::name('users')->field('COUNT(*) total,COUNT(CASE WHEN subscribe = 1 THEN 1 ELSE NULL END) subscount,COUNT(CASE WHEN subscribe = 0 THEN 1 ELSE NULL END ) un_subscount,COUNT(CASE WHEN repeat_subscribe = 1 && subscribe = 1 THEN 1 ELSE NULL END) repeat_subscribe_count,COUNT(CASE WHEN is_second_unsubscribe = 1 THEN 1 ELSE NULL END) as second_unsubscribe_count')
            ->where($where)
            ->whereOr($whereOr)
            ->select();//关注人数
            // dump(Db::name('users')->getLastSql());exit();
            return json($count[0]);
        }else{
            return false;
        }
    }

    public function author(){
        $wechat = $this->config;
        $wechat_author = $this->wechat_author_util;
        $author_code = $wechat_author->getPreAuthCode();
        $redirect_uri = $wechat['redirect_url'];
        //引导授权页
        $author_url = 'https://mp.weixin.qq.com/cgi-bin/componentloginpage?component_appid='.$wechat['appid'].'&pre_auth_code='.$author_code['pre_auth_code'].'&redirect_uri='.$redirect_uri.'&auth_type=3';
        $this->redirect($author_url);
    }

        /**
     * @param auth_code 授权码
     * @param expires_in 过期时间
     */
    public function savewxuser($auth_code,$expires_in){
        $wechat_author = $this->wechat_author_util;
        $query_auth = $wechat_author->query_auth($auth_code);
        $wechat_info = $query_auth['authorization_info'];
        if($this->author_wx_user->where('appid',$wechat_info['authorizer_appid'])->where('authorized',1)->find()) $this->redirect(url('admin/publicnum/index'));
        $authors = $query_auth['authorization_info']['func_info'];
        //获取授权公众号基本信息

        $base_info = $wechat_author->getAuthorizerInfo($wechat_info['authorizer_appid']);
        $wechat_base_info = $base_info['authorizer_info'];

        $data = [
            'uid'                      => session::get('admin_id'),
            'appid'                    => $wechat_info['authorizer_appid'], //公众号appid
            'wxname'                   => $wechat_base_info['nick_name'],   //微信公众号名字
            'headerpic'                => isset($wechat_base_info['head_img']) ? $wechat_base_info['head_img'] : '', //微信公众号头像
            'type'                     => $wechat_base_info['service_type_info']['id'], //微信公众号类型
            'verify_type'              => $wechat_base_info['verify_type_info'], //授权方认证类型
            'wxid'                     => $wechat_base_info['user_name'], //原始id
            'weixin'                   => isset($wechat_base_info['alias']) ? $wechat_base_info['alias'] : '', //微信号
            'qr'                       => $wechat_base_info['qrcode_url'], //二维码图片的URL
            'idc'                      => $wechat_base_info['idc'],
            'principal_name'           => $wechat_base_info['principal_name'], //公众号的主体名称
            'signature'                => $wechat_base_info['signature'], //公众号的主体名称
            'authorizer_access_token'  => $wechat_info['authorizer_access_token'], //授权方接口调用凭据
            'authorizer_expires'       => time() + $expires_in - 200, // 提前200秒过期
            'authorizer_refresh_token' => $wechat_info['authorizer_refresh_token'], //接口调用凭据刷新令牌
            'business_info'            => serialize($wechat_base_info['business_info']), //功能
            'funcscope_category'       => serialize($authors), //授权给开发者的权限集列表
        ];

        //判断该公众号之前是否已授权且以取消授权
        if(($find = $this->author_wx_user->where('appid',$wechat_info['authorizer_appid'])->where('authorized',0)->find())){
            $result = $find['id'];
            $data['authorized'] = 1;
            $this->author_wx_user->save($data,['id' => ['eq',$result]]);
        }else{
            $result = $this->author_wx_user->insertGetId($data);
        }

        if($result){
            $wechat_info = $this->author_wx_user->where('id',$result)->find();
            Session::set('wechat_info' , $wechat_info);
            //同步公众号用户信息
            $this->SyncUserInfo($this->config , $wechat_info);
            $this->redirect(url('admin/publicnum/index'));
        }else{
            $this->error('绑定失败');
        }
    }

    private function SyncUserInfo($config , $author_wx_user){
        $this->users_model = new UsersModel;
        $this->wechat_obj = new WechatThirdUtil($config , $author_wx_user);
        $arr = $this->wechat_obj->getFanIdList();
        if($arr['total'] != 0){
            $j = $arr['total'] / $arr['count'];
            for($i = 0; $i < $j; $i++){
                $chunk_arr = array_chunk($arr['data']['openid'],100);
                foreach($chunk_arr as $v){
                    $openid_list = [];
                    foreach($v as $v2){
                        $openid_list[] = ['openid' => $v2];
                    }
                    $data = $this->wechat_obj->getBatchget($openid_list);
                    $result = $this->users_model->saveAll($data['user_info_list']);
                }
                if($j > $i){
                    $arr = $this->wechat_obj->getFanIdList($arr['next_openid']);
                }
            }
        }
    }

    /**
     * 统计预览
     * @return mixed
     */
    public function sta_preview($id = '')
    {
        if(!empty($id)){
            $admin_id = session::get('admin_id');
            if($admin_id == 1){
                $where = ['id' => ['eq',$id]];
            }else{
                $where = [
                    'uid'=>['eq',$admin_id],
                    'id' => ['eq',$id],
                ];
            }

            $wechat_info = Db::name('author_wx_user')->where($where)->find();
            if(!$wechat_info) return false;
            Session::set('wechat_info' , $wechat_info);
        }elseif(Session::has('wechat_info')){
            $wechat_info = Session::get('wechat_info');
        }else{
            $this->redirect('/admin/publicnum/index');
        }

        $count = Db::name('users')->field('COUNT(*) total,COUNT(CASE WHEN subscribe = 1 THEN 1 ELSE NULL END) subscount,COUNT(CASE WHEN subscribe = 0 THEN 1 ELSE NULL END ) un_subscount,COUNT(CASE WHEN repeat_subscribe = 1 && subscribe = 1 THEN 1 ELSE NULL END) repeat_subscribe_count,COUNT(CASE WHEN is_second_unsubscribe = 1 THEN 1 ELSE NULL END) as second_unsubscribe_count')
                                  ->where('auid',$wechat_info['id'])
                                  ->select();//关注人数
        if($count){
            return json(['status' => 1,'msg' => 'ok' , 'result' => $count[0]]);
        }else{
            return json(['status' => -1,'msg' => 'error']);
        }
    }
}